package snsdbook.servlets.likes;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.SQLUtil;
import util.Util;

/**
 * Servlet implementation class LikeModifyServlet
 */
public class LikeModifyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LikeModifyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  String user = request.getParameter("username");
	  String type = request.getParameter("type");
	  String id = request.getParameter("id");
	  String query = null;
	  if (type.equals("likes")) {
	    query = "SELECT COUNT(likes.id_berita) AS cnt FROM likes " +
	             "WHERE id_berita='" + id +
	             "' AND username='" + user + "'";
	  } else if (type.equals("dislike")) {
	    query = "SELECT COUNT(dislike.id_berita) AS cnt FROM dislike " +
	             "WHERE id_berita='" + id +
	             "' AND username='" + user + "'";
	  } else {
	    Util.PrintAndClose(response, "UNRECOGNIZED TYPE PARAMETER");
	  }

	  String[] answers = SQLUtil.Query(query);

	  String ret = "";
	  
	  if (answers[0].equals("0")) {
	    // Add it
	    ret += "INSERT\n";
	    SQLUtil.Modify("INSERT INTO " + type +
	                   "(id_berita, username) VALUES('" +
	                   id + "', '" + user + "')");
	  } else {
	    // Remove it
	    ret += "DELETE\n";
	    SQLUtil.Modify("DELETE FROM " + type +
	                   " WHERE id_berita='" + id + "' AND" +
	                   " username='" + user + "'");
	  }
	  
	  Util.PrintAndClose(response, ret);
	}

}
